import { loginAPI, getUserDataAPI, getUserInfoAPI } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
import router from '@/router'
import { Message } from 'element-ui'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    userData: {}
  }
}

const state = getDefaultState()

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USEDATA: (state, data) => {
    state.userData = data
  },
  DEL_TOEKN: state => {
    state.token = ''
    removeToken()
    router.replace('/login')
  }
}

const actions = {
  // 用户登录
  // 1.获取数据
  async login (store, loginForm) {
    const { data: res } = await loginAPI(loginForm)
    // 2.存入数据（本地、vuex、cookie）
    setToken(res.data) //存储cookie
    // vuex存储token
    store.commit('SET_TOKEN', res.data)
    // 判断条件密码是否正确
    if (res.success) {
      // 3.跳转页面
      router.push('/dashboard')
      Message.success('登录成功')
    }
  },

  async getUserInfo (store) {
    // 用户基本信息
    const { data: res } = await getUserInfoAPI()
    // 用户详细信息
    const { data: res1 } = await getUserDataAPI(res.data.userId)
    const dataAll = { ...res.data, ...res1.data }
    store.commit('SET_USEDATA', dataAll)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
